/**
 * Created by Administrator on 2016/8/24.
 */
var express = require('express');
var Article = require('../db/article');
var result = require('../utils/result');
var Date1 = require('../utils/DateUtil');
var fs=require('fs');
var router = express.Router();

var path="";
router.post('/save1', function(req, res, next) {
    if(!req.session.path || req.session.path==""){
        var r = result();
        var date = new Date();
        var date2=new Date1().format("yy-MM-dd hh:mm:ss");
        var ms = Date.parse(date);
        path='./public/articles/'+ms+'.html';
        fs.writeFile(path, req.body.content,  function(err) {
            if (err) {
                return console.error(err);
            }
        });
        var article = new Article({
            title:req.body.title,
            content: './articles/'+ms+'.html',
            author:req.session.username,
            authorId:req.session.userid,
            creatTime:date2,
            updateTime:date2,
            describe:req.body.describe
        });
        article.save(function (err, doc) {
            if (err) {
                r.error = err;
                return;
            } else {
                req.session.articleid=doc._id;
                req.session.path=doc.content;
                r.data = 'ok';
            }
            return res.json(doc.title);
        });
    }else {
        var r = result();
        path="./public/"+req.session.path.split('./')[1];
        var date3=new Date1().format("yy-MM-dd hh:mm:ss");
        fs.writeFile(path, req.body.content,  function(err) {
            if (err) {
                return console.error(err);
            }
        });
        var conditions = {_id : req.session.articleid};
        var update     = {$set :{
            title:req.body.title,
            updateTime:date3,
            describe:req.body.describe}
        };
        var options    = {upsert : true};
        Article.update(conditions, update, options, function(error){
            if(error) {
                r.error = err;
                return;
            } else {
                r.data = 'ok';
            }
            return res.json(r);
        });
    }
});
module.exports = router;
